package controller

import (
	"github.com/gin-gonic/gin"
	"hanyun-admin/src/entity"
	"hanyun-admin/src/service"
	"net/http"
	"strconv"
	"time"
)

//数据列表
func GetSysDeptList(c *gin.Context) {
	var dept entity.Dept
	c.Bind(&dept)
	deptList := service.SelectDeptList(dept)
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"data": deptList,
		"msg":  "操作成功",
	})
}

//新增
func AddSysDeptData(c *gin.Context) {
	var dept entity.Dept
	c.BindJSON(&dept)
	dept.CreateTime = time.Now()
	err := service.InsertSysDeptData(dept)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  err,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "操作成功",
	})
}

//编辑
func GetSysDeptInfo(c *gin.Context) {
	deptId, _ := strconv.ParseInt(c.Param("deptId"), 10, 64)
	dept := service.SelectDeptByDeptId(deptId)
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"data": dept,
		"msg":  "操作成功",
	})
}

//更新
func UpdateSysDeptData(c *gin.Context) {
	var dept entity.Dept
	c.BindJSON(&dept)
	err := service.UpdateSysDeptData(dept)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  "操作失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "操作成功",
	})
}

//删除
func DeleteSysDeptData(c *gin.Context) {
	deptId, _ := strconv.ParseInt(c.Param("deptId"), 10, 64)
	err := service.DeleteSysDeptByDeptId(deptId)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  "操作失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "操作成功",
	})
}

//树形部门菜单
func GetDeptTreeList(c *gin.Context) {
	dept := service.GetSysDeptDataList()
	data := service.DeptBuildData(dept)
	result := service.DeptMakeTreeCore(0, data)
	service.DeptArraySort(result)
	deptList := service.BuildDeptTree(result)
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"data": deptList,
		"msg":  "操作成功",
	})
}
